package com.nmc.service.dao.impl;


import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.nmc.service.dao.HospitalDao;
import com.nmc.service.model.Hospital;

/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve Hospital objects.
 *
*/
public class HospitalDaoImpl extends GenericDaoImpl<Hospital, Long> implements HospitalDao {

    public HospitalDaoImpl(Class<Hospital> persistentClass,
			SessionFactory sessionFactory) {
		super(persistentClass, sessionFactory);
		// TODO Auto-generated constructor stub
	}

	public HospitalDaoImpl(Class<Hospital> persistentClass) {
		super(persistentClass);
		// TODO Auto-generated constructor stub
	}

	/**
     * Constructor that sets the entity to User.class.
     */
    public HospitalDaoImpl() {
        super(Hospital.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<Hospital> getHospitalList() {
        return getHibernateTemplate().find("from Hospital u order by u.id");
    }

    /**
     * {@inheritDoc}
     */
    public Hospital saveHospital(Hospital hospital) {
        if (log.isDebugEnabled()) {
            log.debug("hospital's id: " + hospital.getId());
        }
        getHibernateTemplate().saveOrUpdate(hospital);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getHibernateTemplate().flush();
        return hospital;
    }

    /**
     * Overridden simply to call the saveHospital method. This is happenening 
     * because saveHospital flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param hospital obj to save
     * @return the modified hospital (with a primary key set if they're new)
     */
    @Override
    public Hospital save(Hospital hospital) {
        return this.saveHospital(hospital);
    }

	public List<Hospital> searchHospital(int zoneId, String query) {
		List<Hospital> hospitalList = null;
		if(StringUtils.isEmpty(query)){
			hospitalList = getHibernateTemplate().find("from Hospital where zones.id=?",zoneId);
		}
		if(StringUtils.isNotEmpty(query)){
			Query rawquery = getSession().createSQLQuery("select * from hospital where zone_id="+zoneId+" and name like '%"+query+"%'").addEntity(Hospital.class);
			hospitalList = rawquery.list();
		}
		
		return hospitalList;
	}




    
}
